﻿using csLTDMC;
using InspectionMAC.Function;
using System;
using System.Threading;
using System.Collections.Concurrent;
using System.IO;
using LitJson;
using System.Collections.Generic;
using InspectionMAC.Config;
using InspectionMAC.Forms;

namespace InspectionMAC.SystemThread
{
    class AddPointThread02
    {
        public static bool AddPoint_Flowrec = false;
        public static Thread AddPointFlow_Thread = null;
        public static int iAddPoint_Step = 0;

        public static AddPointTask1 TaskGroup1Config { get; private set; }

        private static ConcurrentQueue<bool> objectTriggers = new ConcurrentQueue<bool>();
        private static DateTime _debounceTimerStart;
        private static bool _isDebouncing;

        // 防抖相关变量
        private static DateTime _triggerDebounceStart;
        private static bool _isTriggerDebouncing;

        // 最小触发间隔保护
        private static DateTime _lastTriggerTime = DateTime.MinValue;
        public static int MIN_TRIGGER_INTERVAL_MS;  // 100ms最小触发间隔

        // 触发事件唯一ID
        private static long _triggerCounter = 0;
        private static ConcurrentDictionary<string, bool> _processedTriggers =
            new ConcurrentDictionary<string, bool>();

        public static void LoadTaskConfigs()
        {
            try
            {
                string jsonFilePath = MacTestForm.SettingsFilePath;
                if (!File.Exists(jsonFilePath))
                {
                    Console.WriteLine("配置文件不存在！");
                    return;
                }

                string jsonContent = File.ReadAllText(jsonFilePath);
                JsonData jsonData = JsonMapper.ToObject(jsonContent);

                JsonData task1Data = jsonData["TaskGroup3"];
                TaskGroup1Config = new AddPointTask1
                {
                    Interval = (uint)(int)task1Data["Interval"],
                    DoPin = (ushort)(int)task1Data["DoPin"],
                    ActionType = (ushort)(int)task1Data["ActionType"]
                };

                // 初始化对象触发队列
                for (int i = 0; i < 10; i++) // 假设最多10个物体
                {
                    objectTriggers.Enqueue(false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载配置失败: {ex.Message}");
            }
        }

        public static void AddPoint_Thread()
        {
            LoadTaskConfigs();
            AddPoint_Flowrec = true;
            AddPointFlow_Thread = new Thread(AddPointFlowThread)
            {
                IsBackground = true,
                Priority = ThreadPriority.AboveNormal
            };
            AddPointFlow_Thread.Start();

            iAddPoint_Step = 10;
        }

        private static uint cp3;
        private static void AddPointFlowThread(object obj)
        {
            while (AddPoint_Flowrec)
            {
                switch (iAddPoint_Step)
                {
                    case 0:
                        Thread.Sleep(10);
                        break;

                    case 10:  // 等待触发状态
                        if (DIO_Thread.Di[12] == 1)
                        {
                            cp3 = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0);
                            Console.WriteLine("传感器2编码值" + LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0));
                            // 检查最小触发间隔
                            if ((DateTime.Now - _lastTriggerTime).TotalMilliseconds < MIN_TRIGGER_INTERVAL_MS)
                            {
                                Console.WriteLine($"触发间隔过短，忽略信号: {DateTime.Now:HH:mm:ss.fff}");
                                Thread.Sleep(10);
                                break;
                            }

                            // 生成唯一触发ID
                            string triggerId = $"{DateTime.Now:HHmmssfff}_{Interlocked.Increment(ref _triggerCounter)}";

                            if (_processedTriggers.TryAdd(triggerId, true))
                            {
                                Console.WriteLine($"有效触发: {triggerId}");
                                ProcessPointsForCurrentObject(cp3);
                                _lastTriggerTime = DateTime.Now; // 更新最后触发时间
                            }
                            else
                            {
                                Console.WriteLine($"重复触发已忽略: {triggerId}");
                            }

                            iAddPoint_Step = 15;
                        }
                        break;

                    case 15:  // 等待信号释放
                        if (DIO_Thread.Di[12] == 0)
                        {
                            Thread.Sleep(30);
                            iAddPoint_Step = 10;
                        }
                        break;

                    case 20:
                    case 25:
                    case 30:
                    case 35:
                        Thread.Sleep(10);
                        break;
                }
            }
        }

        private static void ProcessPointsForCurrentObject(uint cp3)
        {
            // 获取当前物料
            var material = MaterialTracker.GetNextPendingMaterial(MaterialTracker.MaterialStatus.Station2Processed);

            if (material == null)
            {
                Console.WriteLine("传感器2: 无待处理物料或状态不符");
                return;
            }

            string materialId = material.Id;

            // 进行掉料检测
            //uint axis0Position = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0);
            bool isDropped = MaterialTracker.CheckMaterialDrop(materialId, cp3);
            if (isDropped)
            {
                // 如果掉料，跳过该物料的后续处理
                Console.WriteLine($"物料{materialId}掉料，跳过工位3处理");
                MaterialTracker.UpdateMaterialStatus(materialId, MaterialTracker.MaterialStatus.Kicked);
                return;
            }
            // 记录传感器二触发位置
            uint currentPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 2);
            MaterialTracker.RecordSensor2Position(materialId, currentPos);
            // 添加工位3的比较点
            ProcessSinglePointWithOffset(TaskGroup1Config,cp3);

            // 更新物料状态
            MaterialTracker.UpdateMaterialStatus(materialId, MaterialTracker.MaterialStatus.Station3Triggered);

            Console.WriteLine($"为物料{materialId}添加工位3比较点");
        }

        private static int w3k=0;
        private static void ProcessSinglePointWithOffset(AddPointTask1 task,uint currentPos)
        {
            //uint currentPos = LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0);
            uint newPos;
            try
            {
                checked
                {
                    newPos = currentPos + task.Interval;
                }
                LTDMC.dmc_compare_add_point(0, 0, newPos, 1, task.ActionType, task.DoPin);
                w3k += 1;
                MacTestForm.macTestForm.AddLog("工位三第" + w3k + "比较点");
                Console.WriteLine("添加比较点:" + newPos + ";" + "DO:" + task.DoPin + ";");
            }
            catch (OverflowException)
            {
                Console.WriteLine("比较点溢位，当前位置" + LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0));
                uint actualPos = unchecked(LTDMC.dmc_get_encoder(DMC300_Info.usCardId[0], 0) + task.Interval);
                //MotionStatus_API.bOverflow = true;
                newPos = unchecked(currentPos + task.Interval);
                LTDMC.dmc_compare_add_point(0, 0, newPos, 1, task.ActionType, task.DoPin);
                Console.WriteLine("添加溢位比较点:" + newPos + ";" + "DO:" + 3 + ";");
            }
        }

        public class AddPointTask1
        {
            public uint Interval { get; set; }
            public ushort DoPin { get; set; }
            public ushort ActionType { get; set; }
        }
    }
}